<script setup lang="ts">
import { ref } from 'vue'
import { LoginPage } from '@fssc/admin'
import Cookie from 'js-cookie'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '../../store'
import { login, captcha } from '../../api/passport-auth'
import { TOKEN_KEY } from '../../util/const'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const hasCaptcha = ref(false)

const captchaImg = ref('')

const verCodeKey = ref('')

const getCaptcha = () => {
  verCodeKey.value = ''
  captchaImg.value = ''
  captcha().then((data) => {
    captchaImg.value = data.image
    verCodeKey.value = data.key
  })
}

const handleLogin = (formData: Record<string, any>, done: () => {}) => {
  const loginData: Record<string, any> = {
    email: formData.email,
    password: window.btoa(formData.password),
  }
  if (verCodeKey.value) {
    loginData.verCodeKey = verCodeKey.value
    loginData.verCode = formData.verCode
  }

  login(loginData)
    .then(async (data) => {
      const redirectUrl = new URL(data)
      const params = Object.fromEntries(redirectUrl.searchParams)
      Cookie.set(TOKEN_KEY, params.token)
      userStore.setToken(params.token)
      await userStore.requestUserInfo();
      done()
      let redirect: string | undefined = route.query.redirect as string | undefined;
      redirect = redirect ? decodeURIComponent(redirect) : '/';
      router.push(redirect);
    })
    .catch((err) => {
      console.error(err)
      if (err && err.code == '500001') {
        hasCaptcha.value = true
        getCaptcha()
      }
      done()
    })
}
</script>
<template>
  <LoginPage
    :has-captcha="hasCaptcha"
    :captcha-img="captchaImg"
    @on-submit="handleLogin"
    @on-get-captcha="getCaptcha"
  />
</template>
